﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVector>
#include <QString>
#include <QStandardPaths>
#include <cstdlib>
#include <direct.h>
#include <cassert>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stdio.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    refreshDPI();

    combo_box_freq[0] = ui->ComboBoxFreq(0);
    combo_box_freq[1] = ui->ComboBoxFreq(1);
    combo_box_freq[2] = ui->ComboBoxFreq(2);
    combo_box_freq[3] = ui->ComboBoxFreq(3);
    combo_box_freq[4] = ui->ComboBoxFreq(4);
    combo_box_freq[5] = ui->ComboBoxFreq(5);
    combo_box_freq[6] = ui->ComboBoxFreq(6);
    combo_box_freq[7] = ui->ComboBoxFreq(7);
    combo_box_freq[8] = ui->ComboBoxFreq(8);
    combo_box_freq[9] = ui->ComboBoxFreq(9);
    combo_box_freq[10] = ui->ComboBoxFreq(10);
    combo_box_freq[11] = ui->ComboBoxFreq(11);
    combo_box_freq[12] = ui->ComboBoxFreq(12);
    combo_box_freq[13] = ui->ComboBoxFreq(13);
    combo_box_freq[14] = ui->ComboBoxFreq(14);
    combo_box_freq[15] = ui->ComboBoxFreq(15);
    combo_box_freq[16] = ui->ComboBoxFreq(16);
    combo_box_freq[17] = ui->ComboBoxFreq(17);
    combo_box_freq[18] = ui->ComboBoxFreq(18);
    combo_box_freq[19] = ui->ComboBoxFreq(19);
    combo_box_freq[20] = ui->ComboBoxFreq(20);
    combo_box_freq[21] = ui->ComboBoxFreq(21);
    combo_box_freq[22] = ui->ComboBoxFreq(22);
    combo_box_freq[23] = ui->ComboBoxFreq(23);
    combo_box_freq[24] = ui->ComboBoxFreq(24);
    combo_box_freq[25] = ui->ComboBoxFreq(25);
    combo_box_freq[26] = ui->ComboBoxFreq(26);
    combo_box_freq[27] = ui->ComboBoxFreq(27);
    combo_box_freq[28] = ui->ComboBoxFreq(28);
    combo_box_freq[29] = ui->ComboBoxFreq(29);
    combo_box_freq[30] = ui->ComboBoxFreq(30);
    combo_box_freq[31] = ui->ComboBoxFreq(31);
    combo_box_freq[32] = ui->ComboBoxFreq(32);
    combo_box_freq[33] = ui->ComboBoxFreq(33);
    combo_box_freq[34] = ui->ComboBoxFreq(34);
    combo_box_freq[35] = ui->ComboBoxFreq(35);
    combo_box_freq[36] = ui->ComboBoxFreq(36);
    combo_box_freq[37] = ui->ComboBoxFreq(37);
    combo_box_freq[38] = ui->ComboBoxFreq(38);
    combo_box_freq[39] = ui->ComboBoxFreq(39);
    combo_box_freq[40] = ui->ComboBoxFreq(40);
    combo_box_freq[41] = ui->ComboBoxFreq(41);
    combo_box_freq[42] = ui->ComboBoxFreq(42);
    combo_box_freq[43] = ui->ComboBoxFreq(43);
    combo_box_freq[44] = ui->ComboBoxFreq(44);
    combo_box_freq[45] = ui->ComboBoxFreq(45);
    combo_box_freq[46] = ui->ComboBoxFreq(46);
    combo_box_freq[47] = ui->ComboBoxFreq(47);
    combo_box_freq[48] = ui->ComboBoxFreq(48);
    combo_box_freq[49] = ui->ComboBoxFreq(49);
    combo_box_freq[50] = ui->ComboBoxFreq(50);
    combo_box_freq[51] = ui->ComboBoxFreq(51);
    combo_box_freq[52] = ui->ComboBoxFreq(52);
    combo_box_freq[53] = ui->ComboBoxFreq(53);
    combo_box_freq[54] = ui->ComboBoxFreq(54);
    combo_box_freq[55] = ui->ComboBoxFreq(55);
    combo_box_freq[56] = ui->ComboBoxFreq(56);
    combo_box_freq[57] = ui->ComboBoxFreq(57);
    combo_box_freq[58] = ui->ComboBoxFreq(58);
    combo_box_freq[59] = ui->ComboBoxFreq(59);
    combo_box_freq[60] = ui->ComboBoxFreq(60);
    combo_box_freq[61] = ui->ComboBoxFreq(61);
    combo_box_freq[62] = ui->ComboBoxFreq(62);
    combo_box_freq[63] = ui->ComboBoxFreq(63);

    line_edit_space[0] = ui->LineEdit(0);
    line_edit_space[1] = ui->LineEdit(1);
    line_edit_space[2] = ui->LineEdit(2);
    line_edit_space[3] = ui->LineEdit(3);
    line_edit_space[4] = ui->LineEdit(4);
    line_edit_space[5] = ui->LineEdit(5);
    line_edit_space[6] = ui->LineEdit(6);
    line_edit_space[7] = ui->LineEdit(7);
    line_edit_space[8] = ui->LineEdit(8);
    line_edit_space[9] = ui->LineEdit(9);
    line_edit_space[10] = ui->LineEdit(10);
    line_edit_space[11] = ui->LineEdit(11);
    line_edit_space[12] = ui->LineEdit(12);
    line_edit_space[13] = ui->LineEdit(13);
    line_edit_space[14] = ui->LineEdit(14);
    line_edit_space[15] = ui->LineEdit(15);
    line_edit_space[16] = ui->LineEdit(16);
    line_edit_space[17] = ui->LineEdit(17);
    line_edit_space[18] = ui->LineEdit(18);
    line_edit_space[19] = ui->LineEdit(19);
    line_edit_space[20] = ui->LineEdit(20);
    line_edit_space[21] = ui->LineEdit(21);
    line_edit_space[22] = ui->LineEdit(22);
    line_edit_space[23] = ui->LineEdit(23);
    line_edit_space[24] = ui->LineEdit(24);
    line_edit_space[25] = ui->LineEdit(25);
    line_edit_space[26] = ui->LineEdit(26);
    line_edit_space[27] = ui->LineEdit(27);
    line_edit_space[28] = ui->LineEdit(28);
    line_edit_space[29] = ui->LineEdit(29);
    line_edit_space[30] = ui->LineEdit(30);
    line_edit_space[31] = ui->LineEdit(31);
    line_edit_space[32] = ui->LineEdit(32);
    line_edit_space[33] = ui->LineEdit(33);
    line_edit_space[34] = ui->LineEdit(34);
    line_edit_space[35] = ui->LineEdit(35);
    line_edit_space[36] = ui->LineEdit(36);
    line_edit_space[37] = ui->LineEdit(37);
    line_edit_space[38] = ui->LineEdit(38);
    line_edit_space[39] = ui->LineEdit(39);
    line_edit_space[40] = ui->LineEdit(40);
    line_edit_space[41] = ui->LineEdit(41);
    line_edit_space[42] = ui->LineEdit(42);
    line_edit_space[43] = ui->LineEdit(43);
    line_edit_space[44] = ui->LineEdit(44);
    line_edit_space[45] = ui->LineEdit(45);
    line_edit_space[46] = ui->LineEdit(46);
    line_edit_space[47] = ui->LineEdit(47);
    line_edit_space[48] = ui->LineEdit(48);
    line_edit_space[49] = ui->LineEdit(49);
    line_edit_space[50] = ui->LineEdit(50);
    line_edit_space[51] = ui->LineEdit(51);
    line_edit_space[52] = ui->LineEdit(52);
    line_edit_space[53] = ui->LineEdit(53);
    line_edit_space[54] = ui->LineEdit(54);
    line_edit_space[55] = ui->LineEdit(55);
    line_edit_space[56] = ui->LineEdit(56);
    line_edit_space[57] = ui->LineEdit(57);
    line_edit_space[58] = ui->LineEdit(58);
    line_edit_space[59] = ui->LineEdit(59);
    line_edit_space[60] = ui->LineEdit(60);
    line_edit_space[61] = ui->LineEdit(61);
    line_edit_space[62] = ui->LineEdit(62);
    line_edit_space[63] = ui->LineEdit(63);

    remain_main_freq[0] = ui->lineEdit_main_freq0;
    remain_main_freq[1] = ui->lineEdit_main_freq1;
    remain_main_freq[2] = ui->lineEdit_main_freq2;
    remain_main_freq[3] = ui->lineEdit_main_freq3;

    for(int i=0; i < 64; i++)
    {
        connect(line_edit_space[i], SIGNAL(editingFinished()), this, SLOT(refresh_DataSize()));
        connect(line_edit_space[i], SIGNAL(textChanged(const QString &)), this, SLOT(refresh_DataSize_all(const QString &)));
    }
    for(int i=0; i < 16; i++)
    {
        connect(combo_box_freq[i*4], SIGNAL(currentIndexChanged(int)), this, SLOT(comboBox_freq_group_0_currentIndexChanged(int)));
        connect(combo_box_freq[i*4+1], SIGNAL(currentIndexChanged(int)), this, SLOT(comboBox_freq_group_1_currentIndexChanged(int)));
        connect(combo_box_freq[i*4+2], SIGNAL(currentIndexChanged(int)), this, SLOT(comboBox_freq_group_2_currentIndexChanged(int)));
        connect(combo_box_freq[i*4+3], SIGNAL(currentIndexChanged(int)), this, SLOT(comboBox_freq_group_3_currentIndexChanged(int)));
    }

    refresh_DataSize();
    comboBox_freq_group_0_currentIndexChanged(0);
    comboBox_freq_group_1_currentIndexChanged(0);
    comboBox_freq_group_2_currentIndexChanged(0);
    comboBox_freq_group_3_currentIndexChanged(0);

    readTxt("thread_config.h");
}


void MainWindow::readTxt(QString file)
{
#ifdef Q_OS_DARWIN
    qDebug() << QDir::homePath()+"/DeskTop/"+ file;
    QFile in_file(QDir::homePath()+"/DeskTop/"+ file);
#else
    qDebug() << file;
    QFile in_file(file);
#endif
    if(!in_file.exists())
    {
        return;
    }
    if(!in_file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return;
    }
    QTextStream infile(&in_file);

    QString freq[9] =
    {
        "0x0",
        "0x100",
        "0x200",
        "0x300",
        "0x400",
        "0x500",
        "0x600",
        "0x700",
        "0x800"
    };
    QString rate[9] =
    {
        "1/4",
        "1/8",
        "1/16",
        "1/32",
        "1/64",
        "1/128",
        "1/256",
        "1/512",
        "1/1024"
    };

    QString str1 = "ROTHD_THREAD";
    QString str2 = "_FREQCFG_VALUE";
    QString str3 = "VALID";
    QString str4 = "_STACKCFG_VALUE";

    QString str5 = "ROTHD_CODE_RAM_VALUE";
    QString str6 = "ROTHD_DATA_RAM_VALUE";
    QString str7 = "ROTHD_CODE_SPACE_VALUE";
    QString str8 = "ROTHD_DATA_SPACE_VALUE";
    QString str9 = "ROTHD_COMMON_DATA_SPACE_VALUE";
    QString str10 = "ROTHD_COLCK_SOURCE_SEL";

    int code_value;
    int data_value;
    int code_space_value;
    int data_space_value;
    int common_data_space_value;
    int clock_source_sel = 0;
    uint32_t threadx_start[64] = {0};
    uint32_t freq_number[64] = {0};
    bool threadx_valid[64];

    int stack_i = 0;
    int freq_i = 0;
    int valid_i = 0;
    while (!infile.atEnd())
    {
        QString s = infile.readLine();
        if(s.contains(str2))
        {
            QString str_temp = str1 + QString::number(freq_i) + str2;
            int xxx = s.indexOf(str_temp);
            if (xxx != -1)//"ROTHD_THREADx_FREQCFG_VALUE"
            {
                bool ok;
                xxx += str_temp.length();
                xxx += 1;
                freq_number[freq_i] = s.mid(xxx).toUInt(&ok, 16);
            }
            freq_i++;
        }
        else if(s.contains(str4))
        {
            QString str_temp = str1+ QString::number(stack_i) + str4;
            int xxx = s.indexOf(str_temp);
            if (xxx != -1)//"ROTHD_THREADx_STACKCFG_VALUE"
            {
                xxx += str_temp.length();
                xxx += 1;
                threadx_start[stack_i] = s.mid(xxx).toUInt();
            }
            stack_i++;
        }
        else if(s.contains(str3))
        {
            if(s.contains(str1 + QString::number(valid_i) + "_VALID"))
            {
                threadx_valid[valid_i] = true;
            }
            else if(s.contains(str1 + QString::number(valid_i) + "_INVALID"))
            {
                threadx_valid[valid_i] = false;
            }
            valid_i++;
        }
        else if(s.contains(str5))
        {
            int xxx = s.indexOf(str5);
            if (xxx != -1)//"ROTHD_CODE_RAM_VALUE"
            {
                xxx += str5.length();
                xxx += 1;
                code_value = s.mid(xxx).toUInt();
            }
        }
        else if(s.contains(str6))
        {
            int xxx = s.indexOf(str6);
            if (xxx != -1)//"ROTHD_CODE_RAM_VALUE"
            {
                xxx += str6.length();
                xxx += 1;
                data_value = s.mid(xxx).toUInt();
            }
        }
        else if(s.contains(str7))
        {
            int xxx = s.indexOf(str7);
            if (xxx != -1)//"ROTHD_CODE_SPACE_VALUE"
            {
                xxx += str7.length();
                xxx += 1;
                code_space_value = s.mid(xxx).toUInt();
            }
        }
        else if(s.contains(str8))
        {
            int xxx = s.indexOf(str8);
            if (xxx != -1)//"ROTHD_DATA_SPACE_VALUE"
            {
                xxx += str8.length();
                xxx += 1;
                data_space_value = s.mid(xxx).toUInt();
            }
        }
        else if(s.contains(str9))
        {
            int xxx = s.indexOf(str9);
            if (xxx != -1)//"ROTHD_COMMON_DATA_SPACE_VALUE"
            {
                xxx += str9.length();
                xxx += 1;
                common_data_space_value = s.mid(xxx).toUInt();
            }
        }
        else if(s.contains(str10))
        {
            int xxx = s.indexOf(str10);
            if (xxx != -1)//"ROTHD_COLCK_SOURCE_SEL"
            {
                xxx += str10.length();
                xxx += 1;
                clock_source_sel = s.mid(xxx).toUInt();
            }
        }
    }
    in_file.close();

    qDebug() << "Read success";
    qDebug() << code_value;
    qDebug() << data_value;
    qDebug() << code_space_value;
    qDebug() << data_space_value;
    qDebug() << common_data_space_value;
    qDebug() << clock_source_sel;
    for(int i=0; i < 64; i++)
    {
        qDebug() << threadx_start[i] << "|0x" << QString::number(freq_number[i],16) << "|" << threadx_valid[i];
    }

    if(code_value == 32*1024)
        ui->comboBox_size->setCurrentIndex(0);
    else if(code_value == 64*1024)
        ui->comboBox_size->setCurrentIndex(1);
    else if(code_value == 96*1024)
        ui->comboBox_size->setCurrentIndex(2);

    ui->comboBox_timerSource->setCurrentIndex(clock_source_sel);


    QVector<int> data_stack_size;
    for(int i=0; i < 64; i++)
    {
        if(freq_number[i] == 0xf0fff000)
            combo_box_freq[i]->setCurrentIndex(0);
        else
        {
            int temp = ((freq_number[i]&0xF0000000)>>28) + 1;
            qDebug() << QString::number((freq_number[i]&0xF0000000)>>28,16) << ":" << temp;
            combo_box_freq[i]->setCurrentIndex(temp);
        }

        if(i < 63)
            line_edit_space[i]->setText(QString::number(threadx_start[i] - threadx_start[i+1],10));
    }
    line_edit_space[63]->setText(QString::number(threadx_start[63]-common_data_space_value,10));

    refresh_DataSize();
    comboBox_freq_group_0_currentIndexChanged(0);
    comboBox_freq_group_1_currentIndexChanged(0);
    comboBox_freq_group_2_currentIndexChanged(0);
    comboBox_freq_group_3_currentIndexChanged(0);


}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::refresh_DataSize_all(const QString &text)
{
    int size_sum = 0;
    for(int i=0; i < 64; i++)
    {
        int temp = line_edit_space[i]->text().toInt(nullptr,10);
        size_sum += temp;
    }
    int data_space_index = ui->comboBox_size->currentIndex();
    ui->lineEdit_remain_data_size->setText(tr("%1").arg(data_space_size[data_space_index]-size_sum));
}

//刷新dpi
void MainWindow::refreshDPI()
{
    //计算dpi
    QList<QScreen*> screens = QApplication::screens();
    QScreen* screen = screens[0];
    qreal dpi = screen->logicalDotsPerInch();
    //计算dpi对应的缩放比例
    double objectRate = dpi/96.0;
    changeObjectSize(*this, objectRate);
    qDebug()<<"width "<<width() << "height "<< height();
    resize(width()*objectRate,height()*objectRate);
}
//修改所有控件尺寸
void MainWindow::changeObjectSize(const QObject &o, double objectRate)
{
    for (int i=0; i<o.children().size(); ++i) {
        QWidget *pWidget = qobject_cast<QWidget *>(o.children().at(i));
        if (pWidget != nullptr) {
            qDebug() << pWidget->width() << pWidget->height();
            //pWidget->resize(pWidget->width()*objectRate, pWidget->height()*objectRate);
            pWidget->setGeometry(pWidget->x()*objectRate,pWidget->y()*objectRate,
                                 pWidget->width()*objectRate, pWidget->height()*objectRate);
            changeObjectSize(*(o.children().at(i)),objectRate);
        }
    }
}

void MainWindow::on_pushButton_clicked()
{

    double freq_sum[4] = {0,0,0,0};
    int size_sum = 0;

    refresh_DataSize();
    comboBox_freq_group_0_currentIndexChanged(0);
    comboBox_freq_group_1_currentIndexChanged(0);
    comboBox_freq_group_2_currentIndexChanged(0);
    comboBox_freq_group_3_currentIndexChanged(0);


    for(int i=0; i < 64; i++)
    {
        int temp = line_edit_space[i]->text().toInt(nullptr,10);
        if(temp % 4 != 0)
        {
            temp = temp + 4 - temp%4;
            //line_edit_space[i]->setText(tr("%1").arg(temp));
        }
        size_sum += temp;
    }
    for(int i=0; i < 16; i++)
    {
        if(combo_box_freq[i*4]->currentIndex() != 0)
            freq_sum[0] += 1.0 / pow(2.0, (combo_box_freq[i*4]->currentIndex()+1));
        if(combo_box_freq[i*4+1]->currentIndex() != 0)
            freq_sum[1] += 1.0 / pow(2.0, (combo_box_freq[i*4+1]->currentIndex()+1));
        if(combo_box_freq[i*4+2]->currentIndex() != 0)
            freq_sum[2] += 1.0 / pow(2.0, (combo_box_freq[i*4+2]->currentIndex()+1));
        if(combo_box_freq[i*4+3]->currentIndex() != 0)
            freq_sum[3] += 1.0 / pow(2.0, (combo_box_freq[i*4+3]->currentIndex()+1));
    }
    int data_space_index = ui->comboBox_size->currentIndex();
    qDebug() << size_sum;
    if(size_sum > data_space_size[data_space_index])
    {
        QMessageBox::warning(this,QString::fromLocal8Bit("生成错误"),QString::fromLocal8Bit("线程栈空间总和大于数据空间"),QMessageBox::Ok);
        return;
    }
    for(int i=0; i < 4; i++)
    {
        qDebug() << freq_sum[i];
        if(freq_sum[i] > 0.25)
        {
            QMessageBox::warning(this,QString::fromLocal8Bit("生成错误"),QString::fromLocal8Bit("线程组")+tr("%1").arg(i)+QString::fromLocal8Bit("频率总和大于1/4"),QMessageBox::Ok);
            return;
        }
    }
#ifdef Q_OS_DARWIN
    if(generate_Code("thread_config.h"))
        QMessageBox::information(this,QString::fromLocal8Bit("成功"),QString::fromLocal8Bit("生成成功: 桌面/thread_config.h"),QMessageBox::Ok);
    else
        QMessageBox::information(this,QString::fromLocal8Bit("错误"),QString::fromLocal8Bit("生成失败: 桌面/thread_config.h"),QMessageBox::Ok);
#else
    if(generate_Code("thread_config.h"))
        QMessageBox::information(this,QString::fromLocal8Bit("成功"),QString::fromLocal8Bit("生成成功"),QMessageBox::Ok);
    else
        QMessageBox::information(this,QString::fromLocal8Bit("错误"),QString::fromLocal8Bit("生成失败"),QMessageBox::Ok);
#endif
}

uint32_t MainWindow::reverseBits(uint32_t n)
{
    uint32_t result = 0;

    result |= (n & 0x0001)<<9;
    result |= (n & 0x0002)<<7;
    result |= (n & 0x0004)<<5;
    result |= (n & 0x0008)<<3;
    result |= (n & 0x0010)<<1;
    result |= (n & 0x0020)>>1;
    result |= (n & 0x0040)>>3;
    result |= (n & 0x0080)>>5;
    result |= (n & 0x0100)>>7;
    result |= (n & 0x0200)>>9;
    return result;
}

bool MainWindow::generate_Code(QString filename)
{
#ifdef Q_OS_DARWIN
    qDebug() << QDir::homePath()+"/DeskTop/"+ filename;
    QFile code_file(QDir::homePath()+"/DeskTop/"+ filename);
#else
    qDebug() << filename;
    QFile code_file(filename);
#endif
    code_file.open(QIODevice::Text | QIODevice::WriteOnly | QIODevice::Truncate);
    if(!code_file.isOpen())
    {
        return false;
    }
    QTextStream out(&code_file);
    int data_space_index = ui->comboBox_size->currentIndex();
    int code_size = code_space_size[data_space_index];
    int data_size = data_space_size[data_space_index];

    QVector<uint32_t> main_freq_values(64,0xf0fff000);
    for(int group = 0; group < 4; group++)
    {
        {
            QList<int> sorted_index;
            QVector<double> main_freqs;
            QVector<int> main_freq_indexs;
            sorted_index.push_front(0);
            for(int i = 0; i < 16; i++)
            {
                double temp = 0;
                if(combo_box_freq[i*4+group]->currentIndex() != 0)
                    temp = 1.0 / pow(2.0, (combo_box_freq[i*4+group]->currentIndex()+1));
                main_freqs.push_back(temp);
                main_freq_indexs.push_back(combo_box_freq[i*4+group]->currentIndex());
            }
            qDebug() << main_freqs;
            for(int i = 1; i < 16; i++)
            {
                qDebug() << sorted_index;
                for(int j=0; j <= i; j++)
                {
                    if(j==i)
                    {
                        sorted_index.push_back(i);
                        break;
                    }
                    if(main_freqs[i] > main_freqs[sorted_index[j]])
                    {
                        qDebug() << j << i << sorted_index;
                        sorted_index.insert(j,i);
                        break;
                    }
                }
            }
            qDebug() << sorted_index;
            uint32_t alreay_use = 0;
            for(int i=0; i < 16; i++)
            {
                int index = sorted_index[i];
                if(main_freq_indexs[index] != 0)
                {
                    if(i > 0)
                    {
                        int last_index = sorted_index[i-1];
                        alreay_use = alreay_use + (uint32_t)(main_freqs[last_index]*1024*4);
                        main_freq_values[index*4+group] =  (main_freq_indexs[index]-1)*0x10000000 + ((reverseBits(alreay_use))<<12);
                    }
                    else
                    {
                        main_freq_values[index*4+group] = (main_freq_indexs[index]-1)*0x10000000;
                    }

                    qDebug() << group << "|" << i << "|" << index << "|" << tr("%1").arg(main_freq_values[index*4+group],4,16);
                }
                else
                    break;
            }
        }
    }

    QVector<int> thread_space_stacks;
    int thread_data_sum = 0;
    thread_space_stacks.push_back(data_size+DATA_RESERVE_SPACE-64);
    for(int i=1; i < 64; i++)
    {
        if(combo_box_freq[i-1]->currentIndex() != 0)
        {
            int temp = line_edit_space[i-1]->text().toInt(nullptr,10);
            if(temp % 4 != 0)
            {
                temp = temp + 4 - temp%4;
                //line_edit_space[i]->setText(tr("%1").arg(temp));
            }
            thread_data_sum += temp;
            if(i > 0)
            {
                thread_space_stacks.push_back(thread_space_stacks[i-1]-temp);
            }
        }
        else
        {
            thread_space_stacks.push_back(thread_space_stacks[i-1]);
        }
    }
    int remain_data_size = data_size - thread_data_sum;

    out << "#define ROTHD_CODE_RAM_VALUE " << code_size + RESERVE_SPACE << endl;
    out << "#define ROTHD_DATA_RAM_VALUE " << data_size + DATA_RESERVE_SPACE << endl << endl;

    out << "#define ROTHD_CODE_SPACE_VALUE " << code_size << endl;
    out << "#define ROTHD_DATA_SPACE_VALUE " << data_size + DATA_RESERVE_SPACE << endl;
    out << "#define ROTHD_COMMON_DATA_SPACE_VALUE " << remain_data_size << endl;
    out << "#define ROTHD_COLCK_SOURCE_SEL " << ui->comboBox_timerSource->currentIndex() << endl << endl << endl;
    for(int i=0; i < 64; i++)
    {
        out << "#define ROTHD_THREAD" << i << "_FREQCFG_VALUE 0x" << QString::number(main_freq_values[i],16) << endl;
        if(main_freq_values[i] != 0xffff)
            out << "#define ROTHD_THREAD" << i << "_VALID" << endl;
        else
            out << "#define ROTHD_THREAD" << i << "_INVALID" << endl;
        out << "#define ROTHD_THREAD" << i << "_STACKCFG_VALUE " << thread_space_stacks[i] << endl << endl;
    }
    out.flush();
    code_file.close();

    QFile lds_file(":/MC3172.lds");
    lds_file.open(QIODevice::Text | QIODevice::ReadOnly);
    QString read_input = QString::fromUtf8(lds_file.readAll());
    lds_file.close();
#ifdef Q_OS_DARWIN
    qDebug() << QDir::homePath()+"/DeskTop/"+ "MC3172.lds";
    QFile lds_out_file(QDir::homePath()+"/DeskTop/"+ "MC3172.lds");
#else
    QFile lds_out_file("MC3172.lds");
#endif
    lds_out_file.open(QIODevice::Text | QIODevice::WriteOnly | QIODevice::Truncate);
    if(!lds_out_file.isOpen())
        return false;
    QTextStream lds_out(&lds_out_file);
    read_input.replace("dEfInE_cOdE_SpACE",QString::number(code_size+RESERVE_SPACE-16,10));
    read_input.replace("dEfInE_DaTa_SpACE",QString::number(remain_data_size,10));
    lds_out_file.write(read_input.toUtf8());
    lds_out_file.flush();
    lds_out_file.close();

    return true;
}


void MainWindow::refresh_DataSize()
{
    int size_sum = 0;
    for(int i=0; i < 64; i++)
    {
        int temp = line_edit_space[i]->text().toInt(nullptr,10);
        if(temp % 4 != 0)
        {
            temp = temp + 4 - temp%4;
            //line_edit_space[i]->setText(tr("%1").arg(temp));
        }
        size_sum += temp;
    }
    int data_space_index = ui->comboBox_size->currentIndex();
    qDebug() << size_sum;
    if(size_sum > data_space_size[data_space_index])
    {
        QMessageBox::warning(this,QString::fromLocal8Bit("错误"),QString::fromLocal8Bit("线程栈空间总和大于数据空间"),QMessageBox::Ok);
        return;
    }

    ui->lineEdit_remain_data_size->setText(tr("%1").arg(data_space_size[data_space_index]-size_sum));
}


void MainWindow::comboBox_freq_group_0_currentIndexChanged(int index)
{
    double freq_sum = 0;
    for(int i=0; i < 16; i++)
    {
        if(combo_box_freq[i*4]->currentIndex() != 0)
        {
            freq_sum += 1.0 / pow(2.0, (combo_box_freq[i*4]->currentIndex()+1));
            line_edit_space[i*4]->setEnabled(true);
        }
        else
        {
            line_edit_space[i*4]->setText("");
            line_edit_space[i*4]->setEnabled(false);
        }

    }
    if(freq_sum > 0.25)
    {
        QMessageBox::warning(this,QString::fromLocal8Bit("错误"),QString::fromLocal8Bit("线程组")+tr("%1").arg(0)+QString::fromLocal8Bit("频率总和大于1/4"),QMessageBox::Ok);
        return;
    }
    ui->lineEdit_main_freq0->setText(QString::number((0.25-freq_sum)*100,'g')+"%");
}

void MainWindow::comboBox_freq_group_1_currentIndexChanged(int index)
{
    double freq_sum = 0;
    for(int i=0; i < 16; i++)
    {
        if(combo_box_freq[i*4+1]->currentIndex() != 0)
        {
            freq_sum += 1.0 / pow(2.0, (combo_box_freq[i*4+1]->currentIndex()+1));
            line_edit_space[i*4+1]->setEnabled(true);
        }
        else
        {
            line_edit_space[i*4+1]->setText("");
            line_edit_space[i*4+1]->setEnabled(false);
        }
    }
    if(freq_sum > 0.25)
    {
        QMessageBox::warning(this,QString::fromLocal8Bit("错误"),QString::fromLocal8Bit("线程组")+tr("%1").arg(1)+QString::fromLocal8Bit("频率总和大于1/4"),QMessageBox::Ok);
        return;
    }
    ui->lineEdit_main_freq1->setText(QString::number((0.25-freq_sum)*100,'g')+"%");

    refresh_DataSize();
}

void MainWindow::comboBox_freq_group_2_currentIndexChanged(int index)
{
    double freq_sum = 0;
    for(int i=0; i < 16; i++)
    {
        if(combo_box_freq[i*4+2]->currentIndex() != 0)
        {
            freq_sum += 1.0 / pow(2.0, (combo_box_freq[i*4+2]->currentIndex()+1));
            line_edit_space[i*4+2]->setEnabled(true);
        }
        else
        {
            line_edit_space[i*4+2]->setText("");
            line_edit_space[i*4+2]->setEnabled(false);
        }
    }
    if(freq_sum > 0.25)
    {
        QMessageBox::warning(this,QString::fromLocal8Bit("错误"),QString::fromLocal8Bit("线程组")+tr("%1").arg(2)+QString::fromLocal8Bit("频率总和大于1/4"),QMessageBox::Ok);
        return;
    }
    ui->lineEdit_main_freq2->setText(QString::number((0.25-freq_sum)*100,'g')+"%");

    refresh_DataSize();
}

void MainWindow::comboBox_freq_group_3_currentIndexChanged(int index)
{
    double freq_sum = 0;
    for(int i=0; i < 16; i++)
    {
        if(combo_box_freq[i*4+3]->currentIndex() != 0)
        {
            freq_sum += 1.0 / pow(2.0, (combo_box_freq[i*4+3]->currentIndex()+1));
            line_edit_space[i*4+3]->setEnabled(true);
        }
        else
        {
            line_edit_space[i*4+3]->setText("");
            line_edit_space[i*4+3]->setEnabled(false);
        }
    }
    if(freq_sum > 0.25)
    {
        QMessageBox::warning(this,QString::fromLocal8Bit("错误"),QString::fromLocal8Bit("线程组")+tr("%1").arg(3)+QString::fromLocal8Bit("频率总和大于1/4"),QMessageBox::Ok);
        return;
    }
    ui->lineEdit_main_freq3->setText(QString::number((0.25-freq_sum)*100,'g')+"%");

    refresh_DataSize();
}

void MainWindow::on_comboBox_size_currentIndexChanged(int index)
{
    refresh_DataSize();
}

